<?php

namespace app\admin\service;

use app\admin\exception\LogicException;
use app\admin\model\Plugin as Model;
use app\admin\validate\PluginValidate as Validate;
use app\common\exception\PluginException;
use app\common\plugins\flow\Install;
use app\common\plugins\flow\UnInstall;
use think\Exception;

class Plugin extends AdminService
{

    protected $staticSources='';
	protected function init()
	{
		$this->model = new Model();
		$this->validate = new Validate();
	}

	/**
	 * 获取未安装的插件
	 * @return \think\response\Json
	 */
	public function getPlugins(){
		$pluginsInfo = [];
		$pluginsPath = app()->getRootPath() . 'plugins';

		if(is_dir($pluginsPath)){
			$dir = opendir($pluginsPath);
			while (($file = readdir($dir)) !== false){
				if($file != '.' && $file != '..' && is_dir($pluginsPath.'\\'.$file) && !is_file($pluginsPath.'\\'.$file.'\\install.lock')){
					$class = '\\plugins\\' . $file .'\\Plugin';
					$pluginsInfo[] = $this->getPluginInfo($class);
				}
			}
		}

		return json([
			'code'  => 0 ,
			'data'  => $pluginsInfo ,
			'count' => count($pluginsInfo),
			'msg'   => ''
		]);
	}

	public function install($plugin=null,$instance=false){
        if(!$instance){
			$class = 'app\\plugins\\'.$plugin.'\\Plugin';

			if(class_exists($class)){
				$plugin = new $class;
			}else{
				throw new LogicException("插件{$plugin}不存在");
			}
		}

        try{
            if((new Install($plugin))->make()){
                if(is_cli()){
                    return true;
                }
                return $this->success('操作成功：安装');
            }
        }catch (PluginException $e){
            if(is_cli()){
                throw new PluginException($e->getMessage());
            }
            throw new LogicException($e->getMessage());
        }


	}


    public function uninstall($plugin=null,$instance=false){
		if(!$instance){
			$plugin = get_plugin_instance($plugin);
		}

		if((new UnInstall($plugin))->make()){
		    if(is_cli()){
		        return true;
            }
		    return $this->success('插件卸载成功');
        }

		if(is_cli()){
		    throw new PluginException('插件卸载失败');
        }

		throw new LogicException('插件卸载失败');


    }

    public function config($flag){
		$configModel = new \app\admin\model\Config();
		$data = $this->request->post();
		$configModel->startTrans();
		$success = 0;
		foreach($data as $key=>$value){
			if($configModel->where('group',$flag)->where('key',$key)->update(['value',$value])){
				$success++;
			}
		}

		if($success == count($data)){
			$configModel->commit();
			return $this->success('配置已保存');
		}
		$configModel->rollback();
		throw new LogicException('配置保存失败');
    }


    public function grid(){
		return  $this->model->where('status',1)->field('is_admin,name,flag,description,icon,author,is_install,is_config,is_menu')->select();
    }

    public function info($flag){
		return $this->model->where('flag',$flag)->find();
    }
}

